/**
 *
 * @param depts
 * @param dept
 * @param userDepts
 * @return boolean
 */
function checkDeptLocationParent(depts,dept,userDepts) {
    let result = false
    let provinceArr = userDepts?.map(x => x.dept.province.id)
    let cityArr = userDepts?.map(x => x.dept.city.id)
    let county = userDepts?.map(x => x.dept.county.id)
    let deptParent = depts.find(x=>x.id==dept.parentId)
    if(!deptParent){
        return result
    }
    result = provinceArr.includes(deptParent.province.id)
      && cityArr.includes(deptParent.city.id)
      && county.includes(deptParent.county.id)

    if(deptParent.parentId){
        result = checkDeptLocationParent(depts,deptParent,userDepts)
    }
    return result
}


/**
 * 根据当前用户的所在地获取同属所在地的所有部门
 * @param {Array} depts
 * @param {Array} userDepts
 *
 */
export function getDeptsByUserDeptsLocation(depts, userDepts) {
    let provinceArr = userDepts?.map(x => x.dept.province.id)
    let cityArr = userDepts?.map(x => x.dept.city.id)
    let county = userDepts?.map(x => x.dept.county.id)
    // 同区域的部门
    let deptArr = depts.filter(dept => {
        return (provinceArr.includes(dept.province.id) || !dept.province.id)
          && cityArr.includes(dept.city.id)
          && county.includes(dept.county.id)
    })
    // 再次判断，同区域的部门里面的父节点是不是同区域，如果父节点是同区域的，那么子节点就不返回
    return deptArr.filter(x=>!checkDeptLocationParent(depts,x,userDepts));
}


/**
 * 找出所有的顶端的父节点，父节点的id在depts.id中
 * @param depts.id
 * @param depts.parentId
 */
export function getParentIdsByDepts(depts,index) {
    if (!depts || !Array.isArray(depts) || depts.length == 0 || depts.length == index) {
        return []
    }
    if(index == null){
        index = 0
    }
    const ids = depts.map(x=>x.id)
    var parentIds = []
    var dept = depts.find(x => x.id === depts[index].parentId)
    if (!dept) {
        if(ids.includes(depts[index].parentId)){
            parentIds.push(depts[index].parentId)
        }else{
            parentIds.push(depts[index].id)
        }
    }
    // 递归调用
    parentIds = parentIds.concat(getParentIdsByDepts(depts,index+1))
    return Array.from(new Set(parentIds))
}

